// 基础配置
const baseConfig = {
  baseURL: "https://8d88-223-74-180-49.ngrok-free.app",
  timeout: 10000,
  header: {
    "content-type": "application/json",
  },
};

// 请求拦截器
const requestInterceptor = (config) => {
  uni.showLoading({
    title: "加载中...",
  });

  // 如果不是完整的URL，添加baseURL
  if (!config.url.startsWith("http")) {
    config.url = baseConfig.baseURL + config.url;
  }

  // 合并默认配置
  config.timeout = config.timeout || baseConfig.timeout;
  config.header = {
    ...baseConfig.header,
    ...config.header,
  };

  return config;
};

// 响应拦截器
const responseInterceptor = (response) => {
  uni.hideLoading();

  // 这里可以根据后端返回的状态码做统一处理
  const { statusCode, data } = response;

  if (statusCode >= 200 && statusCode < 300) {
    return data;
  } else {
    uni.showToast({
      title: data.message || "请求失败",
      icon: "none",
    });
    return Promise.reject(data);
  }
};

// 错误处理
const errorHandler = (error) => {
  uni.hideLoading();
  uni.showToast({
    title: "网络异常，请稍后重试",
    icon: "none",
  });
  return Promise.reject(error);
};

// 封装请求方法
const request = (options = {}) => {
  const config = requestInterceptor(options);

  return new Promise((resolve, reject) => {
    uni.request({
      ...config,
      success: (response) => {
        resolve(responseInterceptor(response));
      },
      fail: (error) => {
        reject(errorHandler(error));
      },
      complete: () => {
        uni.hideLoading();
      },
    });
  });
};

export default request;
